package com.cnap.controller;

import com.cnap.db.entity.IndicatorPO;
import com.cnap.model.common.CommonResult;
import com.cnap.model.common.PageResult;
import com.cnap.model.exception.JsonException;
import com.cnap.model.indicator.*;
import com.cnap.service.ExportService;
import com.cnap.service.IndicatorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 度量模型控制类
 *
 * @author xc
 **/
@Api(tags = "指标管理")
@RestController
@RequestMapping("/api/indicator")
public class IndicatorController {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndicatorController.class);

    private final IndicatorService indicatorService;
    private final ExportService exportService;

    @Autowired
    public IndicatorController(IndicatorService indicatorService, ExportService exportService) {
        this.indicatorService = indicatorService;
        this.exportService = exportService;
    }

    /**
     * 查询指标
     *
     * @param queryIndicatorParam 参数
     * @return 结果
     */
    @ApiOperation(value = "查询指标", notes = "查询指标", httpMethod = "POST")
    @PostMapping("/list")
    public CommonResult<PageResult<IndicatorPO>> listIndicators(@RequestBody QueryIndicatorParam queryIndicatorParam) {
        LOGGER.info("[indicator]: query indicator: {}", queryIndicatorParam);
        PageResult<IndicatorPO> result = indicatorService.findByPage(queryIndicatorParam);
        return CommonResult.success(result);
    }

    /**
     * 查询指标实例
     *
     * @param queryIndicatorParam 参数
     * @return 结果
     */
    @ApiOperation(value = "查询指标实例", notes = "查询指标实例", httpMethod = "POST")
    @PostMapping("/list/case")
    public CommonResult<TreeNode> listIndicatorCases(@RequestBody QueryIndicatorCaseParam queryIndicatorParam) {
        LOGGER.info("[indicator]: query indicator case: {}", queryIndicatorParam);
        TreeNode result = indicatorService.findIndicatorCase(queryIndicatorParam);
        return CommonResult.success(result);
    }

    /**
     * 更新指标
     *
     * @param params 参数
     * @return 结果
     */
    @ApiOperation(value = "更新指标", notes = "更新指标", httpMethod = "POST")
    @PostMapping("/update")
    public CommonResult<String> updateIndicator(@RequestBody List<UpdateIndicatorParam> params) {
        indicatorService.batchUpdateValues(params);
        return CommonResult.success("success");
    }

    @ApiOperation(value = "模糊查询-应用场景", notes = "模糊查询-应用场景", httpMethod = "POST")
    @PostMapping("/info/scene")
    public CommonResult<List<String>> getAppScenesLike(@RequestBody QuerySceneParam querySceneParam) {
        List<String> names = indicatorService.queryScenes(querySceneParam);
        return CommonResult.success(names);
    }

    @ApiOperation(value = "模糊查询-指标名称", notes = "模糊查询-指标名称", httpMethod = "POST")
    @PostMapping("/info/indicator")
    public CommonResult<List<String>> getIndicatorsLike(@RequestBody QueryIndicatorNameParam queryIndicatorNameParam) {
        List<String> names = indicatorService.queryIndicatorNames(queryIndicatorNameParam);
        return CommonResult.success(names);
    }


    /**
     * 导出指标
     *
     * @param request  请求
     * @param response 响应
     */
    @ApiOperation(value = "导出指标", notes = "导出指标", httpMethod = "GET")
    @GetMapping("/export")
    public void exportIndicator(HttpServletRequest request, HttpServletResponse response) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm");
        String fileName = "度量模型" + "-" + LocalDateTime.now().format(dateTimeFormatter);
        setResponse(response, fileName);
        exportService.exportIndicator(request, response);
    }

    /**
     * 设置响应
     *
     * @param response              响应
     * @param fileNameWithoutSuffix 文件名称
     */
    private void setResponse(HttpServletResponse response, String fileNameWithoutSuffix) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode(fileNameWithoutSuffix, "UTF-8").replace("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("unsupport encoding exception: {}", e.getMessage());
            throw new JsonException(500, "内部错误");
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
